import axios from 'axios';
import { Toast } from 'react-vant';
import { getCookies, moveCookies } from '@/utils';

const instance = axios.create({
  baseURL: "/h5_api",
});

instance.interceptors.request.use(
  (config) => {
    const token = getCookies('token');
    if (token) {
        config.headers.token = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  ({ data }) => {
    // 对响应数据做点什么
    const { code } = data || {};
    if (code === "1009" || code === '1008') {
      Toast.info('登录过期，请重新登录')
      moveCookies('token');
      localStorage.clear();
      window.location.href = "/login";
      return data;
    }
    return data;
  },
  (error) => {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export const httpPost = (url, data = {}, config = {}) => {
  return new Promise((resolve, reject) => {
    instance.post(url, data, config).then((res) => {
      if (res?.code === '0000') {
        resolve(res || {})
      } else {
        resolve(false)
        Toast.info(res?.message)
      }
    }).catch((err) => {
      resolve(false)
      Toast.info("网络异常")
    });
  })
};

export const httpGet = (url, data = {}, config = {}) => {
  return instance.get(url, {
    params: data,
    ...config
  });
  // return instance.get(url, { params: data, ...config});
};

export default instance;
